<?php
declare(strict_types=1);

namespace app\store\model;

use app\common\model\AppointmentForm as AppointmentFormModel;

class AppointmentForm extends AppointmentFormModel
{
    public function add($userName, $data)
    {
        $data['name'] = $userName;
        return $this->save($data);
    }

    public function edit($userName, $data)
    {
        $data['name'] = $userName;
        return $this->save($data);
    }

    public function remove()
    {
        // 删除记录
        return $this->delete();
    }

    public function getAll(array $param = [])
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        return $this->with(['carType'])
            ->where($filter)
            ->select();
    }

    public function getList(array $param = [])
    {
        // 检索查询条件
        $filter = $this->getFilter($param);
        // 获取用户列表
        return $this->with(['carType','images'])
            ->where($filter)
            ->order(['create_time' => 'desc'])
            ->paginate(15);
    }

    /**
     * 获取查询条件
     * @param array $param
     * @return array
     */
    private function getFilter(array $param = [])
    {
        // 默认查询条件
        $params = $this->setQueryDefaultValue($param, [
            'search' => '', // 表单所填姓名
            'status' => 0, // 表单状态
            'appointment_type' => 0, // 预约类型
            'form_type' => 0, // 表单类型
        ]);
        // 检索查询条件
        $filter = [];
        // 表单所填姓名
        !empty($params['search']) &&
            ($filter[] = ['name|phone', 'like', "%{$params['search']}%"]);
        // 表单状态
        !empty($param['status']) &&
            ($filter[] = ['status', '=', (int) $param['status']]);
        // 预约类型
        !empty($param['appointment_type']) &&
            ($filter[] = [
                'appointment_type',
                '=',
                (int) $param['appointment_type'],
            ]);
        // 表单类型
        !empty($param['form_type']) &&
            ($filter[] = [
                'form_type',
                '=',
                (int) $param['form_type'],
            ]);
        // 起止时间
        if (!empty($params['betweenTime'])) {
            $times = between_time($params['betweenTime']);
            $filter[] = [
                'time',
                '>=',
                date('Y-m-d H:i:s', $times['start_time']),
            ];
            $filter[] = [
                'time',
                '<',
                date('Y-m-d H:i:s', $times['end_time'] + 86400),
            ];
        }
        return $filter;
    }

    public function switchStatus(int $status)
    {
        return $this->save(['status' => $status]);
    }
}
